package com.bawei.lib_net

import android.util.Log
import com.bawei.lib_net.interceptor.BasicParamsInterceptor
import com.bawei.lib_net.interceptor.HeaderInterceptor
import com.bawei.lib_net.interceptor.RequestCacheInterceptor
import com.bawei.lib_net.interceptor.ResponseCacheInterceptor
import com.bawei.lib_net.interceptor.RetryInterceptor
import com.bawei.lib_net.interceptor.SignInterceptor
import com.bawei.lib_net.interceptor.TokenInterceptor
import com.google.gson.GsonBuilder
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

class RetrofitFactory private constructor(){

    private val retrofit: Retrofit
    //缓存位置
    fun createCache(): Cache {
        var file = File("/sdcard/Music")
        return Cache(file,10*1024*1024)
    }
    init {
        retrofit = Retrofit.Builder()
            .baseUrl("http://10.161.9.80:7015")
            .addConverterFactory(GsonConverterFactory.create()) // 恢复为默认gson
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(createOkHttpClient())
            .build()
    }

    /**
     * Create OkHttp Client
     */
    private fun createOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(TokenInterceptor()) //token拦截器
            .addInterceptor(SignInterceptor()) //签名sign拦截器
            .addInterceptor(HeaderInterceptor()) //请求头拦截器
            .addInterceptor(BasicParamsInterceptor()) //请求参数拦截器
            .addInterceptor(RetryInterceptor(5))//失败重试拦截器
            .cache(createCache()) //配置缓存路径
            .addInterceptor(RequestCacheInterceptor()) //缓存拦截器
            .addNetworkInterceptor(ResponseCacheInterceptor()) //缓存拦截器
            .addInterceptor(HttpLoggingInterceptor()) //日志拦截器
//            .addInterceptor(createNormalErrorHttpCodeInterceptor())
            .addInterceptor(createLoggingInterceptor())
            // 兜底拦截器，防止ProtocolException导致崩溃
            .addInterceptor { chain ->
                try {
                    chain.proceed(chain.request())
                } catch (e: java.net.ProtocolException) {
                    // 这里可以做日志、弹窗等兜底处理
                    // 返回一个空的Response防止崩溃
                    okhttp3.Response.Builder()
                        .request(chain.request())
                        .protocol(okhttp3.Protocol.HTTP_1_1)
                        .code(999)
                        .message("ProtocolException: ${e.message}")
                        .body(okhttp3.ResponseBody.create(null, ""))
                        .build()
                }
            }
            .sslSocketFactory(
                SSLSocketFactoryUtil.createSSLSocketFactory(),
                SSLSocketFactoryUtil.createTrustAllManager()
            )
            .hostnameVerifier(SSLSocketFactoryUtil.TrustAllHostnameVerifier())//域名认证
            .build()
    }


    /**
     * create logging interceptor and set level
     */
    private fun createLoggingInterceptor(): Interceptor {
        return HttpLoggingInterceptor().apply { level= HttpLoggingInterceptor.Level.BODY }
    }

    companion object{
        //双重校验锁
        private val instance:RetrofitFactory by lazy(LazyThreadSafetyMode.SYNCHRONIZED){ RetrofitFactory()}
        val TIMEOUT=30L
        fun getRetrofitFactory():RetrofitFactory{
            return instance
        }
    }

    fun <T>create(service:Class<T>):T{
        return retrofit.create(service)
    }


}